//
//  PopoverAnimator.swift
//  weibo_swift
//
//  Created by dulinlong on 15/7/1.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit

class PopoverAnimator: NSObject ,UIViewControllerTransitioningDelegate ,UIViewControllerAnimatedTransitioning{

    //展现视图的大小
    var presentFrame = CGRectZero
    //是剖展现的标志
    var isPresented = false
    
    //返回负责转场的控制器对象
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        let pc = PopoverPresentaionController(presentedViewController: presented, presentingViewController: presenting)
        pc.presentFrame = presentFrame
        return  pc
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        if isPresented{
            //0.获得要加载动画的视图
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            // 1. 将 toView 添加到容器视图
            transitionContext.containerView()?.addSubview(toView!)
            
            // 2. 动画实现
            toView?.transform = CGAffineTransformMakeScale(1.0, 0)
            toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                toView?.transform = CGAffineTransformIdentity
                }) { (_) -> Void in
                    // 3. *** 结束动画 - 告诉系统转场动画已经结束
                    transitionContext.completeTransition(true)
            }
        }else{
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                fromView?.transform = CGAffineTransformMakeScale(1.0, 0.0001)
                }, completion: { (_) -> Void in
                    
                    fromView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
            
        }
        
    }

    
}
